﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Linq;

namespace Mimoza.Common.Instrumental
{
    public class Registry
    {
        public Registry(string subKeyName)
        {
            RegistryKey localMachineKey = Microsoft.Win32.Registry.LocalMachine;

            m_registryKey = localMachineKey.OpenSubKey(subKeyName,true);

            if (m_registryKey == null)
            {
                Common.Logger.Log.Warn("Registry: key is missing - '{0}'.", subKeyName);

                CreateKeyTree(subKeyName, localMachineKey);

                if (m_registryKey == null)
                {
                    Common.Logger.Log.Error("Registry: error in creation key - '{0}'.", subKeyName);
                    return;
                }
            }
        }

        private void CreateKeyTree(string subKeyName, RegistryKey localMachineKey)
        {
            try
            {
                string[] subKeys = subKeyName.Split('\\');
                foreach (string keyName in subKeys)
                {
                    if (m_registryKey == null) m_registryKey = localMachineKey;
                    m_registryKey = m_registryKey.CreateSubKey(keyName);
                    if (m_registryKey == null) break;
                }
            }
            catch (System.Exception exp)
            {
                Common.Logger.Log.Error("Registry.CreateKeyTree: error in creation key - '{0}' error - '{1}'.", 
                    subKeyName, exp.ToString());

            }
        }

        public void CheckAndRewrite<T>(string valueName, T value) where T : class
        {
            if (m_registryKey == null) return;
            if (value == null) return;

            T currentValue = m_registryKey.GetValue(valueName) as T;

            Common.Logger.Log.Trace("Registry: CheckAndRewrite name - '{0}' currentValue - '{1}' value - '{2}'.", 
                valueName, currentValue, value);

            if (currentValue!=null && currentValue.Equals(value)) return;

            if (value is string)
                m_registryKey.SetValue(valueName, value, RegistryValueKind.String);
            else
                m_registryKey.SetValue(valueName, value, RegistryValueKind.DWord);

            m_bModified = true;
        }

        public void DeleteValue(string valueName)
        {
            if (m_registryKey.GetValueNames().ToList().Exists(x => x == valueName))
            {
                m_registryKey.DeleteValue(valueName);
                m_bModified = true;
            }
        }

        public bool IsModified
        {
            get { return m_bModified; }
        }

        RegistryKey m_registryKey;
        bool m_bModified = false;
    }
}
